package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Handles the getting the configuration from the library properties file
 * @author Alex Perkins
 *
 */
public class ConfigurationHelper {

	public static Properties prop = new Properties();
	private static boolean debugMode = Boolean.parseBoolean(ConfigurationHelper.getProperty("debug"));
	
    static {
    	
    	InputStream input  = null;
    	
        try {
        	String workingDir = System.getProperty("user.dir");
        	String path = workingDir + File.separator + "library.properties";
        	debug("Loading Properties from: '" + path + "'");
        	input = new FileInputStream(path);
        	prop.load(input);
        } 
        catch (IOException e) {
            print("Error loading configuration. Cause: " + e.getMessage());
        }
        catch(Exception ex){
        	print("Error loading configuration. Cause: " + ex.getMessage());
        }
        finally{
        	try{
        		if(input != null){
        			input.close();
        		}
        	}
        	catch(IOException e){
        		print("couldn't close input stream. Cause : " + e.getMessage());
        	}
        }
    }

    public static String getProperty(String key) {
    	String value = prop.getProperty(key);
    	String out = "Property: ["+key + "='" + value + "']";
    	debug(out);
        return value;
    }
    
    public static int getIntProperty(String key) {
    	String value = prop.getProperty(key);
    	String out = "Proterty: ["+key + "='" + value + "']";
    	debug(out);
        return Integer.parseInt(value);
    }
    
    public static String getProperty(String key, String id) {
    	String aggregateKey = id + "." + key;
    	return getProperty(aggregateKey);
    }
    
    public static int getIntProperty(String key, String id) {
    	String aggregateKey = id + "." + key;
        return getIntProperty(aggregateKey);
    }
    
    private static void print(String msg){
    	System.out.println(msg);
    }
    
    /**
	 * Checks if the server is in debug mode before printing to console
	 * @param msg
	 */
	private static void debug(String msg){
		if(debugMode){
			print(msg);
		}
	}

}
